package com.lyrcsoft;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
 * @author fujc-dev@qq.com
 * @date 2023/8/1 10:41
 */
public class PipedInputStreamExample {

    public static void main(String[] args) throws Exception {

        // 创建一对PipedInputStream和PipedOutputStream
        PipedInputStream input = new PipedInputStream();
        PipedOutputStream output = new PipedOutputStream(input);

        // 创建一个写线程
        Thread writerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 写入一些数据到PipedOutputStream
                    output.write("Hello, World! xxxxx".getBytes());
                    output.close();
                    // 关闭PipedOutputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        // 创建一个读线程
        Thread readerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 读取PipedInputStream中的数据
                    int data;
                    while ((data = input.read()) != -1) {
                        System.out.print((char) data); // 将数据打印到控制台
                    }
                    input.close(); // 关闭PipedInputStream
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        // 启动写线程和读线程
        writerThread.start();
        readerThread.start();

        // 等待写线程和读线程完成
        writerThread.join();
        readerThread.join();
    }
}

